package com.guonl.open.api.response;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;


@Data
@ApiModel(value = "接口返回对象", description = "接口返回对象")
public class OpenApiResult<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 成功标志
     */
    @ApiModelProperty(value = "成功标志")
    private boolean success = true;

    /**
     * 返回处理消息
     */
    @ApiModelProperty(value = "返回处理消息")
    private String message = "操作成功！";

    /**
     * 返回代码
     */
    @ApiModelProperty(value = "返回代码")
    private Integer code = 200;

    /**
     * 返回数据对象 data
     */
    @ApiModelProperty(value = "返回数据对象")
    private T result;

    /**
     * 时间戳
     */
    @ApiModelProperty(value = "时间戳")
    private long timestamp = System.currentTimeMillis();

    public OpenApiResult() {

    }

    public boolean isSuccess() {
        return success;
    }

    public OpenApiResult<T> success(String message) {
        this.message = message;
        this.code = 200;
        this.success = true;
        return this;
    }


    public static <T> OpenApiResult<T> ok() {
        OpenApiResult<T> r = new OpenApiResult<>();
        r.setSuccess(true);
        r.setCode(200);
        r.setMessage("成功");
        return r;
    }

    public static <T> OpenApiResult<T> ok(String msg) {
        OpenApiResult<T> r = new OpenApiResult<>();
        r.setSuccess(true);
        r.setCode(200);
        r.setMessage(msg);
        return r;
    }

    public static <T> OpenApiResult<T> ok(T data) {
        OpenApiResult<T> r = new OpenApiResult<>();
        r.setSuccess(true);
        r.setCode(200);
        r.setResult(data);
        return r;
    }

    public static <T> OpenApiResult<T> error(String msg) {
        return error(500, msg);
    }

    public static <T> OpenApiResult<T> error(int code, String msg) {
        OpenApiResult<T> r = new OpenApiResult<>();
        r.setCode(code);
        if (msg.indexOf("\\n[ErrorCode]: null") >= 0) {
            msg = msg.substring(0, msg.indexOf("\\n[ErrorCode]: null"));
        }
        r.setMessage(msg);
        r.setSuccess(false);
        return r;
    }


}
